//
//  LSZ.swift
//  醒浪微博
//
//  Created by 雷顺哲 on 16/7/11.
//  Copyright © 2016年 LSZ. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

//微博appkey
let WeiboAppKey = "1314685476"
//微博appsecret
let WeoboAppSecret = "1553e1aa50e258e9c0545f05a1b9c3b8"
//微博授权回调页
let WeiboRedirect_Url = "http://user.qzone.qq.com/"

class LSZOAuthViewController: UIViewController {
    // MARK:懒加载控件
    private lazy var webView: UIWebView = UIWebView()
    
    override func loadView() {
        //        自定义视图
        webView.delegate = self
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        setUpUI()
        requestOAuthLogin()
    }
    
    // MARK:请求方法
    private func requestOAuthLogin() {
        //        请求地址
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Url)"
        //        准备请求对象
        let request = NSURLRequest(URL: NSURL(string: url)!)
        //        加载请求
        webView.loadRequest(request)
    }
    
    // MARK:navigationItem的按钮设置及点击事件
    private func setUpUI() {
        navigationItem.title = "微博登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self , action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self , action: "autoFillAction")
    }
    
    @objc private func cancelAction() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func autoFillAction() {
        //        自动填充
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '18707218175'; document.getElementById('passwd').value = '980202473'")
    }
     
    
    
}










//定义延展类

extension LSZOAuthViewController: UIWebViewDelegate {
    //    将要加载请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.URL else{
            return false
        }
        //        获取url的绝对地址如果是对的,就往下执行等会好去code
        if !url.absoluteString.hasPrefix(WeiboRedirect_Url){
            return true
        }
        
        if let query = url.query where query.hasPrefix("code="){
            //            截取code
            let code = query.substringFromIndex("code=".endIndex)
            //            将截取的code传出去
//            requestAccesstoken(code)
            
            LSZUserAccountViewModel.sharedUserAccount.requestAccesstoken(code, callBack: { (isSuccess) -> () in
                
                if isSuccess {
//                    登录成功
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVCNotification, object: self)
                    })
                    
                } else {
                    SVProgressHUD.showErrorWithStatus("登录失败")
                }
            })

                        
        } else {
            
            dismissViewControllerAnimated(true, completion: nil)
        }
        
        return false
    }
    //    开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    //    加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //    加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
    
}

